package http

import (
	"crypto/tls"
	"os"

	"gitee.com/mkwchecking/sr-core/yerr"
)

func NewTLS(cfg *SSL) (*tls.Config, error) {
	if cfg == nil {
		return nil, yerr.ErrBizParamRequired.Error()
	}

	certContent, keyContent := getFromFile(cfg.Cert), getFromFile(cfg.Key)

	cert, err := tls.X509KeyPair([]byte(certContent), []byte(keyContent))
	if err != nil {
		return nil, err
	}
	return &tls.Config{
		Certificates: []tls.Certificate{cert},
	}, nil
}

func getFromFile(path string) string {
	if inf, err := os.Stat(path); err == nil && !inf.IsDir() {
		// is real path
		res, _ := os.ReadFile(path)
		return string(res)
	}
	return path
}
